<template>
	<view class="content">
		<!-- 导航栏 + 轮播图 + 搜索栏 + 金刚区 -->
		<view class="carousel-container">
			<!-- 自 定义导航栏 -->
			<view class="custom-navbar">
				<image class="logo" src="../../static/logo.png" mode=""></image>
			</view>

			<!-- 搜索栏 -->
			<view class="searchBox">
				<uni-search-bar class="uni-mt-10" radius="100" placeholder="请输入想要搜索的商品" clearButton="auto"
					cancelButton="none" @focus="goClass()" />
			</view>

			<!-- 轮播图 -->
			<swiper class="swiper" indicator-dots circular autoplay>
				<swiper-item v-for="(item, index) in swiperImages" :key="index">
					<image :src="item" class="swiper-image"></image>
				</swiper-item>
			</swiper>

			<view class="content-top-radius">
				<!-- 金刚区 -->
				<view class="kingkong-area">
					<view class="kingkong-item" v-for="(item, index) in jingangList" :key="index"
						@click="goJingang(item)">
						<image class="image01" :src="item.icon" mode="aspectFit"></image>
					</view>
				</view>

				<!-- 内容 -->
				<view class="contentBox">
					<view class="img01" @click="goTagGoodsList(5)"></view>
					<view class="img02" @click="goClassGoodsList(32)"></view>
					<view class="img03" @click="goTagGoodsList(4)"></view>
				</view>
				<!-- 商品 -->
				<view class="goodsContentBox">
					<image class="goodsTitleImage"
						src="https://beauty-of-face.oss-cn-shanghai.aliyuncs.com/H5/goodsTitle.png" mode=""></image>
					<view class="goods-list">
						<view class="goodsItem" v-for="(item, index) in goodsList" :key="index"
							@click="goGoodsDetail(item)">
							<image :src="item.pictureIntegrationDtoS[0].pictureUrl" class="goodsImage"
								mode="aspectFill">
							</image>
							<view class="goodsInfo">
								<p class="goodsTitle">{{ item.commodityName }}</p>
								<view class="priceAndButton">
									<p class="goodsPrice">
										￥{{ item.commoditySpecificationBasicInformationDto.commoditySpecificationAttributeInfoDto.sellingPrice }}
									</p>
								</view>
							</view>
						</view>
					</view>
				</view>
				<view style="height: 100rpx;"></view>
			</view>

			<!-- 推广码 弹出层 -->
			<uni-popup ref="popup" type="center">
				<view class="poster-popup" @tap="onCanvasClick">
					<canvas canvas-id="canvasOne"
						:style="{ width: screenWidth * 0.7 + 'px', height: canvasHeight + 'px' }"></canvas>
				</view>
			</uni-popup>
			<uni-popup ref="popup02" type="center">
				<view class="noBuyCommodity">
					<p class="title">温馨提示</p>
					<p class="tishi">购买报单商品享受推广资格</p>
					<view class="" style="display: flex;justify-content: center;">
						<view class="button01" @click="close02()">
							取消
						</view>
						<view class="button02" @click="goClass()">
							前往购买
						</view>
					</view>
				</view>
			</uni-popup>
		</view>
	</view>
</template>

<script>
	import {
		getGoods
	} from '@/api/goods.js';
	import {
		invitationRecord,
		getUserInfo,
		getIsBuyCommodity
	} from '@/api/user.js';
	import {
		checkLoginStatus
	} from '@/utils/auth';
	import {
		getQrCode,
		getQrCodeBag
	} from '@/api/extension.js';
	export default {
		data() {
			return {
				swiperImages: [
					'https://beauty-of-face.oss-cn-shanghai.aliyuncs.com/H5/bag01.png',
					'https://beauty-of-face.oss-cn-shanghai.aliyuncs.com/H5/bag02.png'
				],
				jingangList: [{
						id: 1,
						icon: 'https://beauty-of-face.oss-cn-shanghai.aliyuncs.com/H5/jingang01.png',
						url: ''
					},
					{
						id: 2,
						icon: 'https://beauty-of-face.oss-cn-shanghai.aliyuncs.com/H5/jingang02.png',
						url: ''
					},
					{
						id: 3,
						icon: 'https://beauty-of-face.oss-cn-shanghai.aliyuncs.com/H5/jingang03.png',
						url: ''
					},
					{
						id: 4,
						icon: 'https://beauty-of-face.oss-cn-shanghai.aliyuncs.com/H5/jingang04.png',
						url: ''
					}
				],
				goodsList: [],
				userId: '',
				bagList: [],
				userInfo: {},
				userName: '',
				qrImg: '',
				currentBackground: '',
				screenWidth: uni.getSystemInfoSync().screenWidth,
				canvasTempFilePath: '', // 用于存储生成的临时图片路径
				isBuyCommodity: ''
			};
		},
		computed: {
			canvasHeight() {
				return 400; // 固定高度，可以根据实际情况调整
			}
		},
		onLoad(option) {
			const url = new URL(window.location.href);
			// 使用 URLSearchParams 获取 pid 参数
			const pid = url.searchParams.get('pid');
			console.log(pid, "pid"); // 输出: 1
			if (pid) {
				localStorage.setItem('pid', pid);
				console.log("有pid，存储");
			}
		},
		onShow() {
			// getIsBuyCommodity().then(res => {
			// 	this.isBuyCommodity = res.data
			// })
			this.getUser()
			this.getGoodsList();
			this.loadBagList();
			// const pid = localStorage.getItem('pid');
			// if (pid && checkLoginStatus()) {
			// 	this.bindUser(pid);
			// }
		},
		methods: {
			getUser() {
				getUserInfo().then(res => {
					this.userInfo = res.data;
					this.userId = res.data.id
					const pid = uni.getStorageSync('pid');
					if (pid && pid != '-1' && checkLoginStatus()) {
						this.bindUser(pid);
					}
					if (!this.userInfo.nickName && res.data.code == 200) {
						uni.redirectTo({
							url: '/pages/my/setting/index'
						});
					}
				})
			},
			loadBagList() {
				const params = {
					pageSize: 99,
					pageNumber: 1
				};
				getQrCodeBag(params).then(res => {
					this.bagList = res.data.records;
				});
			},
			openPosterPopup(bagList) {
				console.log(bagList, "bagList")
				this.currentBackground = bagList[0].posterAddress;
				this.initData().then(() => {
					console.log('准备绘制的元素:', {
						currentBackground: this.currentBackground,
						qrImg: this.qrImg,
						userName: this.userName,
						screenWidth: this.screenWidth,
						canvasHeight: this.canvasHeight
					});
					this.$refs.popup.open();
					this.$nextTick(() => {
						this.mergeImages();
					});
				}).catch(err => console.error('初始化数据失败:', err));
			},
			async initData() {
				try {
					const [qrCodeRes, userInfoRes] = await Promise.all([
						getQrCode(),
					]);

					this.qrImg = qrCodeRes.data;
					this.userName = this.userInfo.nickName;

					console.log('初始化数据完成:', {
						qrImg: this.qrImg,
						userName: this.userName
					});
				} catch (err) {
					throw new Error('初始化数据失败');
				}
			},
			mergeImages() {
				let context = uni.createCanvasContext('canvasOne', this);
				context.clearRect(0, 0, this.screenWidth * 0.7, this.canvasHeight);
				this.downloadAndDrawBackground(context);
			},
			downloadAndDrawBackground(context) {
				console.log(this.currentBackground, "this.currentBackground")
				uni.downloadFile({
					url: this.currentBackground,
					success: (downloadRes) => {
						if (downloadRes.statusCode === 200) {
							const backgroundTempFilePath = downloadRes.tempFilePath;
							console.log('背景图片下载成功:', backgroundTempFilePath);
							context.drawImage(backgroundTempFilePath, 0, 0, this.screenWidth * 0.7, this
								.canvasHeight);
							context.draw(true, () => {
								console.log('背景绘制完成，准备绘制二维码...');
								this.drawQrCode(); // 下载并绘制二维码，不传递context
							});
						} else {
							console.error('背景图片下载失败:', downloadRes);
						}
					},
					fail: (err) => console.error('背景图片下载失败:', err)
				});
			},
			drawQrCode() {
				let context = uni.createCanvasContext('canvasOne', this); // 每次绘制时重新创建context
				uni.downloadFile({
					url: this.qrImg,
					success: (qrDownloadRes) => {
						if (qrDownloadRes.statusCode === 200) {
							const qrTempFilePath = qrDownloadRes.tempFilePath;
							console.log('二维码下载成功:', qrTempFilePath);

							const qrX = this.screenWidth * 0.7 - 68;
							const qrY = this.canvasHeight - 70;
							context.drawImage(qrTempFilePath, qrX, qrY, 42, 42);
							context.draw(true, () => {
								console.log('二维码绘制完成，准备绘制文本...');
								this.drawText(); // 绘制文本，不传递context
							});
						} else {
							console.error('二维码下载失败:', qrDownloadRes);
						}
					},
					fail: (err) => console.error('二维码下载失败:', err)
				});
			},
			drawText() {
				let context = uni.createCanvasContext('canvasOne', this); // 每次绘制时重新创建context
				context.setFontSize(14);
				context.fillStyle = '#fff';
				const nameY = this.canvasHeight - 40;
				const nameWidth = 220;

				context.fillText(this.userName, (this.screenWidth * 0.7 - nameWidth) / 2, nameY);

				context.draw(true, () => {
					console.log('文本绘制完成，准备转换画布为图像...');
					this.convertCanvasToImage(); // 转换画布为图像，不传递context
				});
			},
			convertCanvasToImage() {
				let context = uni.createCanvasContext('canvasOne', this);
				context.draw(true, () => {
					console.log("绘制完成，准备转换为临时文件...");
					uni.canvasToTempFilePath({
						destWidth: this.screenWidth * 0.7,
						destHeight: this.canvasHeight,
						canvasId: 'canvasOne',
						// fileType: 'jpg',
						success: (res) => {
							console.log("转换成功:", res.tempFilePath);
							this.canvasTempFilePath = res.tempFilePath; // 保存临时文件路径
						},
						fail: (err) => {
							console.error('转换画布为临时文件失败:', err);
						}
					});
				});
			},
			onCanvasClick() {
				if (this.canvasTempFilePath) {
					uni.previewImage({
						urls: [this.canvasTempFilePath],
						longPressActions: {
							itemList: ['保存图片'],
							success: () => {},
							fail: (err) => console.error('长按保存失败:', err)
						}
					});
				} else {
					console.warn('没有可用的临时文件路径');
				}
			},
			goJingang(e) {
				switch (e.id) {
					case 1:
						uni.navigateTo({
							url: '/pages/index/articleList/index?type=1'
						});
						break;
					case 2:
						uni.navigateTo({
							url: '/pages/index/articleList/index?type=3'
						});
						break;
					case 3:
						console.log(this.userInfo.subcommissionLevelId, "this.isBuyCommodity")
						if (this.userInfo.isEnablePromotion == '0') {
							this.openPosterPopup(this.bagList);
						} else {
							this.$refs.popup02.open();
						}
						break;
					case 4:
						uni.navigateTo({
							url: '/pages/my/profit/index'
						});
						break;
				}
			},
			getGoodsList() {
				const params = {
					tagIds: [1],
					pageSize: 20,
					pageNumber: 1
				};
				getGoods(params).then(res => {
					this.goodsList = res.data.records;
				});
			},
			goGoodsDetail(item) {
				uni.navigateTo({
					url: `/pages/classification/goodsDetail/index?id=${item.id}`
				});
			},
			goTagGoodsList(e) {
				uni.navigateTo({
					url: `/pages/index/goodsList/index?tagId=${e}`
				});
			},
			goClassGoodsList(e) {
				uni.navigateTo({
					url: `/pages/index/goodsList/index?classifyId=${e}`
				});
			},
			goClass() {
				uni.switchTab({
					url: '/pages/classification/index'
				});
			},
			close02() {
				this.$refs.popup02.close()
			},
			bindUser(pid) {
				console.log(this.userId, "this.userId")
				const data = {
					launchCustomerUserId: pid,
					userUnId: null,
					userId: this.userId
				};
				return invitationRecord(data).then((res) => {
					console.log("绑定成功，删除pid", pid);
					uni.removeStorageSync('pid');
					if (res.code == 200) {
						uni.showToast({
							icon: "none",
							title: '绑定成功！'
						});
					}
				}).catch(err => {
					console.log("绑定失败，删除pid", err);
					uni.removeStorageSync('pid');
					uni.showToast({
						icon: "none",
						title: '绑定失败，请重试！'
					});
					throw err;
				});
			}
		}
	};
</script>

<style lang="scss">
	@import '@/uni.scss';

	canvas {
		width: 70vw;
		height: calc(70vw * 0.5);
		/* 根据宽高比计算高度 */
	}

	.content {
		background-color: $uni-bg-color-grey;
		position: relative; // 相对定位以确保子元素可以绝对定位
	}

	.carousel-container {
		position: relative; // 绝对定位父容器
		z-index: 1; // 确保轮播图及其子元素不会覆盖自定义导航栏
	}

	.custom-navbar {
		display: flex;
		align-items: center;
		padding: 0 20rpx;
		// height: 88rpx;
		position: absolute; // 设置为绝对定位
		top: 80rpx;
		left: 0;
		right: 0;
		z-index: 9; // 确保它位于其他内容之上

		.logo {
			width: 160rpx;
			height: 68rpx;
			margin-right: 20rpx;
		}

		.navbar-title {
			font-size: 36rpx;
			color: #333;
		}
	}

	.swiper {
		width: 100%;
		height: 1130rpx;
	}

	.swiper-image {
		width: 100%;
		height: 100%;
	}

	.searchBox {
		position: absolute;
		left: 0;
		right: 0;

		&.searchBox {
			top: 148rpx; // 根据导航栏高度调整顶部位置
			z-index: 10;
		}


	}

	.content-top-radius {
		width: 100%;
		position: absolute;
		top: 1080rpx;
		left: 0;
		right: 0;
		z-index: 10;
		background-color: #EBF0E3;
		// background: linear-gradient(to bottom, #f3e2c0, #fff 220rpx, #fff 100%);
	}

	.kingkong-area {
		margin: 20rpx 30rpx;
		padding: 20rpx 0rpx;
		border-radius: 40rpx;
		height: 200rpx;
		display: flex;
		justify-content: center;
		background-image: url('https://beauty-of-face.oss-cn-shanghai.aliyuncs.com/H5/jingangBag.png');
		background-size: 100%;
		background-repeat: no-repeat;

		.kingkong-item {
			width: 25%;
			display: flex;
			flex-direction: column;
			align-items: center;

			.image01 {
				width: 120rpx;
				height: 168rpx;
				margin-bottom: 10rpx;
			}
		}
	}

	.contentBox {
		display: flex;
		flex-wrap: wrap;
		gap: 10rpx;
		margin: 20rpx 30rpx;
		padding: 20rpx;
		background-image: url('https://beauty-of-face.oss-cn-shanghai.aliyuncs.com/H5/mofangBag.png');
		background-size: 100%;
		background-repeat: no-repeat;

		.img01 {
			width: 49%;
			height: 170rpx;
			background-image: url('https://beauty-of-face.oss-cn-shanghai.aliyuncs.com/H5/more01.png');
			background-size: 100%;
			background-repeat: no-repeat;

			.icon {
				width: 96rpx;
				height: 80rpx;
				float: right;
				margin: 60rpx 40rpx 0rpx 0rpx;
			}
		}

		.img02 {
			width: 49%;
			height: 170rpx;
			background-image: url('https://beauty-of-face.oss-cn-shanghai.aliyuncs.com/H5/more02.png');
			background-size: 100%;
			background-repeat: no-repeat;

			.icon {
				width: 96rpx;
				height: 80rpx;
				float: right;
				margin: 60rpx 40rpx 0rpx 0rpx;
			}
		}

		.img03 {
			width: 100%;
			height: 200rpx;
			background-image: url('https://beauty-of-face.oss-cn-shanghai.aliyuncs.com/H5/gogogo.png');
			background-size: 100%;
			background-repeat: no-repeat;

			.icon {
				width: 160rpx;
				height: 80rpx;
				float: right;
				margin: 70rpx 40rpx 0rpx 0rpx;
			}
		}
	}

	.goodsContentBox {
		margin: 30rpx;
		display: flex;
		flex-direction: column;

		.goodsTitleImage {
			width: 100%;
			height: 200rpx;
			margin: -60rpx auto;
		}

		.goods-list {
			display: flex;
			flex-wrap: wrap;
			gap: 20rpx;
			margin-top: 60rpx;

			.goodsItem {
				width: calc(50% - 12rpx); // 两个商品之间有20rpx的间隔
				border-radius: 40rpx;
				overflow: hidden;
				box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.1);
				background-image: url('https://beauty-of-face.oss-cn-shanghai.aliyuncs.com/H5/goodsBag.png');
				background-size: 100% 100%;

				.goodsImage {
					width: 320rpx;
					height: 320rpx;
					margin: 10rpx;
					border-radius: 20rpx;
				}

				.goodsInfo {
					margin: 0rpx 20rpx;

					.goodsTitle {
						font-size: 28rpx;
						font-weight: bold;
						color: #333;
						line-height: 1.2em;
						height: 2.4em;
						/* 固定高度，2行文字 */
						overflow: hidden;
						text-overflow: ellipsis;
						display: -webkit-box;
						-webkit-line-clamp: 2;
						-webkit-box-orient: vertical;
					}

					.priceAndButton {
						display: flex;
						justify-content: space-between;
						align-items: center;
						height: 60rpx;

						.goodsPrice {
							font-size: 32rpx;
							color: #7AAD5B;
							font-weight: bold;
							margin-bottom: 10rpx;
						}

					}
				}
			}
		}
	}

	.noBuyCommodity {
		width: 466rpx;
		height: 324rpx;
		background: linear-gradient(to bottom, #7AAD5B, #FFF0D6);
		border-radius: 20rpx;
		padding: 20rpx;

		.title {
			font-weight: bold;
			font-size: 30rpx;
			color: #333333;
			line-height: 34rpx;
			text-align: center;
			margin: 30rpx;
		}

		.tishi {
			font-weight: 400;
			font-size: 28rpx;
			color: #333333;
			line-height: 34rpx;
			text-align: center;
			background-color: none;
			margin-bottom: 80rpx;
		}

		.button01 {
			width: 177rpx;
			height: 62rpx;
			border-radius: 10rpx;
			border: 2rpx solid #7AAD5B;
			font-weight: 400;
			font-size: 26rpx;
			color: #7AAD5B;
			text-align: center;
			line-height: 62rpx;
			margin-right: 20rpx;
		}

		.button02 {
			width: 177rpx;
			height: 62rpx;
			background: #7AAD5B;
			border-radius: 10rpx;
			font-weight: 400;
			font-size: 26rpx;
			color: #FFFFFF;
			text-align: center;
			line-height: 62rpx;
		}
	}
</style>